<template>
    <!-- <el-dropdown trigger="hover">
      <i class="el-icon-message message-icon"></i>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item><span><i class="el-icon-message-solid"></i>系统通知</span></el-dropdown-item>
        <el-dropdown-item @click.native="onOpen"><span><i class="el-icon-chat-line-round"></i>消息中心</span></el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown> -->
    <mchat
      v-show="display"
      ref="mchat"
      :config="config"
      :chats="chats"
      :mine="mine"
      @chatEvent="handleChatEvent"
      @talkEvent="talkEvent"
      @sendMessage="sendMessage"
      @loadHistory="handleHistory"
    >
      <mchat-right-box>
        <template slot-scope="props">
          <mchat-group-list
            v-if="props.chat.type == 'group'"
            :notices="props.chat.notices"
            :userList="props.chat.userList"
            :filter-user-method="filterUser"
            @click="handleRightEvent"
          ></mchat-group-list>
          <div v-else>发挥你的想象</div>
        </template>
      </mchat-right-box>
    </mchat>
</template>

<script>
import { mapGetters } from "vuex";
import { IM } from "@/api";

var gsocket = null;
var gsocketTimeId = null;

export default {
  name: "MsgCenter",
  props: {
    value: {
      type: Boolean,
      default: {},
    },
  },
  watch: {
    value(newVal, oldVal) {
      this.display = true;
    },
  },
  computed: {
    ...mapGetters(["userinfo"]),
    //我的信息
    mine() {
      return {
        // 昵称
        username: this.userinfo.realName,
        // 用户id
        id: this.userinfo.userId,
        //状态
        status: "online",
        //签名
        sign: "与其感慨路难行,不如马上出发！",
        avatar: this.userinfo.headIcon,
      };
    },
  },
  data() {
    return {
      //是否显示
      display: false,
      //获取主面板列表信息，下文会做进一步介绍
      config: {
        // 是否有下拉按钮
        downBtn: true,
        // 是否有右侧抽屉
        rightBox: true,
        // 简约模式
        brief: true,
        // 是否开启桌面消息提醒，即在浏览器之外的提醒
        notice: false,
        // 设定
        voice: false,
      },
      //会话
      chats: [],
    };
  },
  created() {
    this.connectWebsocket();
  },
  mounted(){

  },
  methods: {
    //建立Websocket连接
    connectWebsocket() {
      var _self = this;
      if (top != window) return;
      let websocketId = "";
      if (_self.mine.id != "" && _self.mine.id) websocketId = _self.mine.id;
      IM.PreConnect(websocketId).then((res) => {
        var url = res.server;
        if (gsocket) gsocket.close();
        gsocket = null;
        gsocket = new WebSocket(url);
        gsocket.onopen = function (e) {
          console.log("websocket connect");
          _self.onOpen(); //建立连接成功
        };
        gsocket.onmessage = function (e) {
          try {
            console.log(e);
            let msg = JSON.parse(JSON.parse(e.data));
            _self.onMessage.call(_self, msg); //消息推送
          } catch (e) {
            console.log(e);
            return;
          }
        };
        gsocket.onclose = function (e) {
          console.log("websocket disconnect");
          gsocket = null;
          // clearTimeout(gsocketTimeId);
          // gsocketTimeId = setTimeout(function () {
          //   _self.connectWebsocket.call(_self);
          // }, 5000);
        };
        gsocket.onerror = function (e) {
          console.log("websocket error");
          gsocket = null;
          // clearTimeout(gsocketTimeId);
          // gsocketTimeId = setTimeout(function () {
          //   _self.connectWebsocket.call(_self);
          // }, 5000);
        };
      });
    },
    //建立连接成功
    onOpen() {
      //获取会话
      IM.GetChats(this.mine.id).then((res) => {
        this.chats = res;
      });
    },
    //消息推送
    onMessage(msg) {
      if(msg.type === 'message'){
        //聊天消息推送
        if(msg.content.fromid !== this.mine.id) 
          this.$im.emit("getMessage", msg.content);
      }else if(msg.type === 'online'){
        //上线下线推送
        for (let i = 0; i < this.chats.length; i++) {
          if(this.chats[i].id === msg.content.id)
            this.chats[i].online =  msg.content.online;
        }
      }
    },
    //发送消息
    sendMessage(data) {
      console.log("发送内容", { data });
      const { mine, to, content, timestamp, type } = data;
      let message = {
        //消息来源用户名
        username: mine.username,
        //消息来源用户头像
        avatar: mine.avatar,
        //消息的来源ID（如果是私聊，则是用户id，如果是群聊，则是群组id）
        id: to.id,
        //聊天窗口来源类型，从发送消息传递的to里面获取
        type: to.type,
        //消息内容
        content,
        //消息id，可不传。除非你要对消息进行一些操作（如撤回）
        cid: 0,
        //是否我发送的消息，如果为true，则会显示在右方
        mine: true,
        //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
        fromid: mine.id,
        //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
        timestamp,
      };
      let toMessage = JSON.parse(JSON.stringify(message));
      if(to.type === "friend"){
        //单聊
        toMessage.id = mine.id;
        toMessage.mine = false;

        IM.SendMsg({
          senderWebsocketId: mine.id,
          receiveWebsocketId: to.id,
          message: JSON.stringify({type: 'message', content: toMessage}),
          isReceipt: false
        }).then((res) => {
          this.$refs.mchat.getMessage(message);
        });
      }else{
        //群聊
        toMessage.mine = false;

        IM.SendChannelMsg({
          websocketId: mine.id,
          channel: to.id,
          message: JSON.stringify({type: 'message', content: toMessage})
        }).then((res) => {
          this.$refs.mchat.getMessage(message);
        });
      }
    },
    handleChatEvent(event, data) {
      console.log("窗口事件", { event, data });
      let channels = this.chats;
      let len = channels.length;
      if (len < 1) return;
      let ary = [];
      switch (event) {
        case "removeChat":
          // for (let i = 0; i < len; i++) {
          //   let model = channels[i];
          //   if (model.id != data.id) {
          //     ary.push(model);
          //   }
          // }
          // this.chats = ary;
          break;
        case "chatMin":
        case "chatClose":
          this.display = false;
          break;
      }
    },
    filterUser(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleRightEvent(event) {
      console.log("右边框事件", event);
    },
    handleHistory(callBack) {
      let history = [
        // {
        //   username: "历史记录",
        //   avatar: require("./avatar/temp2.jpg"),
        //   id: 1,
        //   type: "group",
        //   content: "audio[https://www.w3school.com.cn/i/horse.mp3]",
        //   cid: parseInt(Math.random() * 10, 10),
        //   mine: false,
        //   fromid: 3,
        //   timestamp: new Date(),
        // },
        // {
        //   username: "历史记录",
        //   avatar: require("./avatar/temp2.jpg"),
        //   id: 1,
        //   type: "group",
        //   content: "audio[https://www.w3school.com.cn/i/horse.mp3]",
        //   cid: parseInt(Math.random() * 10, 10),
        //   mine: false,
        //   fromid: 3,
        //   timestamp: new Date(),
        // },
        // {
        //   username: "历史记录",
        //   avatar: require("./avatar/temp2.jpg"),
        //   id: 1,
        //   type: "group",
        //   content: "audio[https://www.w3school.com.cn/i/horse.mp3]",
        //   cid: parseInt(Math.random() * 10, 10),
        //   mine: false,
        //   fromid: 3,
        //   timestamp: new Date(),
        // },
        // {
        //   username: "历史记录",
        //   avatar: require("./avatar/temp2.jpg"),
        //   id: 1,
        //   type: "group",
        //   content: "audio[https://www.w3school.com.cn/i/horse.mp3]",
        //   cid: parseInt(Math.random() * 10, 10),
        //   mine: false,
        //   fromid: 3,
        //   timestamp: new Date(),
        // },
      ];
      callBack(history);
    },
    talkEvent(event, data) {
      console.log("谈话内容", { event, data });
    },
    //添加回话
    // handleAddChat() {
    //   let chatId = parseInt(Math.random() * 10, 10);
    //   let newChat = {
    //     id: chatId,
    //     name: "新会话",
    //     type: "friend",
    //     avatar: require("./avatar/temp2.jpg"),
    //   };
    //   this.chats.push(newChat);
    // },
    handleDelChat() {
      this.chats.pop();
    },
  },
};
</script>

<style lang="less" scoped>
</style>